package ltd.hxya.novel.rabbitmq.aspect;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Aspect
@Slf4j
public class RabbitAckAspect {

    @Pointcut("@annotation(ltd.hxya.novel.common.anno.RabbitAck)")
    public void rabbitAck(){}

    @AfterReturning(value = "rabbitAck()")
    public void ack(JoinPoint joinPoint) throws IOException {
        long deliveryTag = 0;
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof Message){
                deliveryTag = ((Message) arg).getMessageProperties().getDeliveryTag();
            }
            if (arg instanceof Channel){
                ((Channel) arg).basicAck(deliveryTag,true);
            }
        }
    }

    @AfterThrowing(pointcut = "rabbitAck()",throwing = "e")
    public void noAck(JoinPoint joinPoint,Exception e) throws IOException {
        e.printStackTrace();
        long deliveryTag = 0;
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof Message){
                deliveryTag = ((Message) arg).getMessageProperties().getDeliveryTag();
            }
            if (arg instanceof Channel){
                ((Channel) arg).basicNack(deliveryTag,false,false);
            }
        }
    }
}
